﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using FRL.DebtChased.ChildWindows;
using FRL.DebtChased.Extensions;
using FRL.DebtChased.Silverlight.Library.RichContentService;
using FRL.DebtChased.Silverlight.Library;
using FRL.DebtChased.ChaseWorkspace;

#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG

namespace FRL.DebtChased.Views
{
    public partial class ChaseScreenCtrl : UserControl
    {
        public ChaseScreenCtrl()
        {

            InitializeComponent();


            this.DebtDetailViewState = DebtDetailViewState.Collapsed;

        }

        public void PostMainLoad()
        {
            // Setup controls
            swapPanel.PostSupportDataLoad();

            // Load the chase session
            _refeshChaseSession();
        }

		/////////////////////////////////////////////////////////////
		// Attributes

		private int m_iChaseOffset = -1;


        /////////////////////////////////////////////////////////////
        // Debt Details Control

        private GridLength _gridRowHeightZero = new GridLength(0);
        private GridLength _debtDetailsNormalRowHeight = new GridLength(250);
        private GridLength _debtDetailsWideRowHeight = new GridLength(500);
        
        private DebtDetailViewState _debtDetailViewState = DebtDetailViewState.Normal;
        public DebtDetailViewState DebtDetailViewState
        {
            get { return _debtDetailViewState; }
            set
            {
                if (value != _debtDetailViewState)
                {
                    if (value == DebtDetailViewState.Collapsed)
                    {
                        this.LayoutRoot.RowDefinitions[3].Height = _gridRowHeightZero;
                        this.gridLeftGrid.RowDefinitions[1].Height = GridLength.Auto;
                        this.gridLeftGrid.RowDefinitions[2].Height = GridLength.Auto;
                    }
                    else
                    {
                        this.LayoutRoot.RowDefinitions[3].Height = GridLength.Auto;
                        this.gridLeftGrid.RowDefinitions[1].Height = _gridRowHeightZero;
                        this.gridLeftGrid.RowDefinitions[2].Height = _gridRowHeightZero;
                    }
                }
                _debtDetailViewState = value;
            }
        }
 

		/////////////////////////////////////////////////////////////
		// Construction


		/////////////////////////////////////////////////////////////
		#region Event handlers and Operations - Account Position

		private void butPreviousAccount_Click(object sender, RoutedEventArgs e)
		{
#if DEBUG
			Debug.Assert(CachedData.Singleton.ChaseItems != null);
			Debug.Assert(CachedData.Singleton.ChaseItems.Count > 0);
			Debug.Assert(m_iChaseOffset > 0);
#endif // #if DEBUG

			// Load the previous account
			_loadAccount(CachedData.Singleton.ChaseItems[m_iChaseOffset - 1].AccountId);

		}

		private void butNextAccount_Click(object sender, RoutedEventArgs e)
		{
#if DEBUG
			Debug.Assert(CachedData.Singleton.ChaseItems != null);
			Debug.Assert(CachedData.Singleton.ChaseItems.Count > 0);
			Debug.Assert(m_iChaseOffset < (CachedData.Singleton.ChaseItems.Count - 1));
#endif // #if DEBUG

			// Load the next account
			_loadAccount(CachedData.Singleton.ChaseItems[m_iChaseOffset + 1].AccountId);

		}

		private void butAccountPositionMenu_Click(object sender, RoutedEventArgs e)
		{

			// If the menu is not visible...
			if (chaseAccountMenuCtrl.Visibility == System.Windows.Visibility.Collapsed)
			{

				// Drop the chase menu
				chaseAccountMenuCtrl.PreVisible();
				chaseAccountMenuCtrl.Visibility = System.Windows.Visibility.Visible;

			}
			else
			{

				// Hide the chase menu
				chaseAccountMenuCtrl.Visibility = System.Windows.Visibility.Collapsed;

			}

		}


		public void _setupChasePositionControls()
		{

			// If the chase is empty...
			if ((CachedData.Singleton.ChaseItems == null) || (CachedData.Singleton.ChaseItems.Count == 0))
			{
#if DEBUG
				Debug.Assert(m_iChaseOffset == -1);
#endif // #if DEBUG

				// Set the position label
				txbChasePosition.Text = "[EMPTY]";

				// Enable/disable buttons
				butPreviousAccount.IsEnabled = false;
				butNextAccount.IsEnabled = false;

			}
			else
			{
#if DEBUG
				Debug.Assert(m_iChaseOffset >= 0);
				Debug.Assert(m_iChaseOffset < CachedData.Singleton.ChaseItems.Count);
#endif // #if DEBUG

				// Set the position label
				txbChasePosition.Text = string.Format("{0}/{1}", m_iChaseOffset + 1, CachedData.Singleton.ChaseItems.Count);

				// Enable/disable buttons
				butPreviousAccount.IsEnabled = (m_iChaseOffset > 0);
				butNextAccount.IsEnabled = (m_iChaseOffset < (CachedData.Singleton.ChaseItems.Count - 1));

			}

		}

		#endregion Event handlers and Operations - Account Position

		/////////////////////////////////////////////////////////////
		#region Event Handlers

        public void OnMouseLeftButtonDown()
        {

            // If the drop-down is viisble...
            if (chaseAccountMenuCtrl.Visibility == System.Windows.Visibility.Visible)
                chaseAccountMenuCtrl.Visibility = System.Windows.Visibility.Collapsed;
        }

        public void OnMenuItemClicked(DebtChasedWebsiteMenuCtrl.eMenuItem menuItemId)
        {
            if (menuItemId != DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_DebtDetails)
                DebtDetailViewState = DebtDetailViewState.Collapsed;

            CoSearchPanel.Visibility = (menuItemId == DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_Agent) ? Visibility.Visible : Visibility.Collapsed;
            ElectoralPanel.Visibility = (menuItemId == DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_Agent) ? Visibility.Visible : Visibility.Collapsed;

            // Compare menu items
            switch (menuItemId)
            {
                case DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_Contacts:

                    // Show contacts swap panel
                    swapPanel.SwapPanels(SwapPanel.ePanel.Contacts);

                    break;
                case DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_DebtDetails:

                    swapPanel.SwapPanels(SwapPanel.ePanel.Contacts);
                    if (DebtDetailViewState == DebtDetailViewState.Collapsed)
                    {
                        // Make sure the debt-details are visible
                        DebtDetailViewState = DebtDetailViewState.Normal;
                    }
                    break;
                case DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_Communications:
                    break;
                case DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_Tools:
                    swapPanel.SwapPanels(SwapPanel.ePanel.Summary);
                    break;
                case DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_Comments:
                    break;
                case DebtChasedWebsiteMenuCtrl.eMenuItem.ChaseScreen_Agent:
                    //swapPanel.SwapPanels(SwapPanel.ePanel.Agent);
                    swapPanel.SwapPanels(SwapPanel.ePanel.Contacts);


                    break;

                case DebtChasedWebsiteMenuCtrl.eMenuItem.Admin_Invoicing:
                    swapPanel.SwapPanels(SwapPanel.ePanel.Invoicing);
                    break;

            } // switch

        }

		#endregion Event Handlers

		/////////////////////////////////////////////////////////////
		#region Operations

		public void ShowCallResultsWnd()
		{

			// Get all debtor numbers
			List<ContactPointTransport> debtorContactPoints = swapPanel.contactsPanel.GetDebtorContactPoints(false);

			// Open call-debtor result window
			CallDebtorResultsWnd wnd = new CallDebtorResultsWnd(debtorContactPoints);
			wnd.Closed += new EventHandler(CallDebtorResultsWnd_Closed);
			wnd.Show();

		}

		void CallDebtorResultsWnd_Closed(object sender, EventArgs e)
		{

			// Get the window refernece
			CallDebtorResultsWnd wnd = sender as CallDebtorResultsWnd;
			if (wnd.DialogResult ?? false)
			{

				// Reload the context account
				ReloadContextAccount();

			}

		}

		private void _setAccount(AccountTransport account)
		{

			// Make this the context account
			CachedData.Singleton.ContextAccount = account;

			// Find the offset for this account
			m_iChaseOffset = CachedData.Singleton.FindOffsetByAccountId(account.AccountId);

			// Set controls
			tbAccountRef.Text = account.FRLReference;

			// Update panels
			swapPanel.Set(account);
            commentsCtrl.Account = account;
			debtSummaryCtrl.Set(account);
            ctrlDebtDetails.Account = account;

			// Update buttons
			_setupChasePositionControls();

		}

		public void ReloadContextAccount()
		{
#if DEBUG
			Debug.Assert(m_iChaseOffset != -1);
#endif // #if DEBUG

			// Load the account
			int iAccountId = CachedData.Singleton.ChaseItems[m_iChaseOffset].AccountId;
			_loadAccount(iAccountId);

		}

		#endregion Operations

		/////////////////////////////////////////////////////////////
		#region Operations loading and saving data

		private void _refeshChaseSession()
		{

			// Show hourglass
			MainPage.Singleton.hourglassCtrl.IncShowCount(true);

			// Load real or fake chasing data
#if USEFAKEDATA

			// Create event
			object[] results = new object[1];
			results[0] = CachedData.GetDummyChaseSessionItemTransportList();
			GetChaseSessionItemsCompletedEventArgs e = new GetChaseSessionItemsCompletedEventArgs(
				results,
				null,
				false,
				null
			);

			// Call completed event
			proxy_GetChaseSessionItemsCompleted(null, e);

#else

			// Start by downloading the supporting data
			RichContentServiceClient proxy = new RichContentServiceClient();
			proxy.GetChaseSessionItemsCompleted += new EventHandler<GetChaseSessionItemsCompletedEventArgs>(proxy_GetChaseSessionItemsCompleted);
			proxy.Endpoint.Address = ExtensionsForSilverlight.CreateDebtChasedEndpoint();
			proxy.GetChaseSessionItemsAsync();

#endif // #if USEFAKEDATA

		}

		void proxy_GetChaseSessionItemsCompleted(object sender, GetChaseSessionItemsCompletedEventArgs e)
		{

			// Hide hourglass
			MainPage.Singleton.hourglassCtrl.IncShowCount(false);

			// Get the result
			if (e.Error != null)
				MessageBoxes.PopupMessage(e.Error.Message);
			else if (e.Result == null)
				MessageBoxes.PopupMessage_InternalError("Failed to load chase session from server.");
			else
			{

				// Update the cached data
				CachedData.Singleton.AddIncoming(e.Result);

			}

			// Update the controls
			m_iChaseOffset = (
					(CachedData.Singleton.ChaseItems == null)
					||
					(CachedData.Singleton.ChaseItems.Count == 0)
					) ? -1 : 0;
			_setupChasePositionControls();

			// Load the first account...
			if (m_iChaseOffset == 0)
			{
				int iAccountId = CachedData.Singleton.ChaseItems[m_iChaseOffset].AccountId;
				_loadAccount(iAccountId);
			}

		}

		private void _loadAccount(int iAccountId)
		{

			// Show hourglass
			MainPage.Singleton.hourglassCtrl.IncShowCount(true);

			// Load real or fake chasing data
#if USEFAKEDATA

			// Create event
			object[] results = new object[1];
			results[0] = CachedData.GetDummyAccountTransport(iAccountId);
			GetAccountTransportCompletedEventArgs e = new GetAccountTransportCompletedEventArgs(
				results,
				null,
				false,
				null
			);

			// Call completed event
			proxy_GetAccountTransportCompleted(null, e);

#else

			// Download the account
			RichContentServiceClient proxy = new RichContentServiceClient();
			proxy.GetAccountTransportCompleted += new EventHandler<GetAccountTransportCompletedEventArgs>(proxy_GetAccountTransportCompleted);
			proxy.Endpoint.Address = ExtensionsForSilverlight.CreateDebtChasedEndpoint();
			proxy.GetAccountTransportAsync(iAccountId);

#endif // #if USEFAKEDATA

		}

		void proxy_GetAccountTransportCompleted(object sender, GetAccountTransportCompletedEventArgs e)
		{

			// Hide hourglass
			MainPage.Singleton.hourglassCtrl.IncShowCount(false);

			// Get the result
			if (e.Error != null)
				MessageBoxes.PopupMessage(e.Error.Message);
			else if (e.Result == null)
				MessageBoxes.PopupMessage_InternalError("Failed to load account from server.");
			else
			{

				// Update the cached data
				CachedData.Singleton.AddIncoming(e.Result);

				// Set controls
				_setAccount(e.Result);

			}

		}

		#endregion Operations loading and saving data

        private void debtDetailTabCtrl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int item = ((TabControl)sender).SelectedIndex;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }


	}

    public enum DebtDetailViewState
    {
        Collapsed,
        Normal,
        Wide
    }
    
}
